'use strict';

const Controller = require('egg').Controller;

const sequelize = require('sequelize').Sequelize;
const Op = sequelize.Op;

class UserController extends Controller {
  constructor(ctx) {
    super(ctx);
  }
  async login() {
    const { ctx } = this;
    let { accountName, password } = ctx.request.body;

    if (!accountName) ctx.throw(400, '用户名不能为空');
    if (!password) ctx.throw(400, '密码不能为空');

    const token = await ctx.service.user.login(accountName, password);
    ctx.body = { token };
  }
  async verified() {
    const { ctx, config } = this;
    ctx.body = ctx.state.user;
  }

  async get() {
    const { ctx, config } = this;
    let user = ctx.state.user;
    let id = ctx.query.id ? ctx.query.id : user.id;
    const userInfo = await ctx.service.user.get(id);
    ctx.body = userInfo
  }

  async list() {
    const { ctx } = this;
    let user = ctx.state.user;
    if (user.role === 'customer') {
      ctx.throw(403, "用户权限不足！");
    }

    const pageNo = Number(ctx.query.pageNo || 1);
    const pageSize = Number(ctx.query.pageSize || 20);
    const { id, idCard, nickName, role } = ctx.query;

    let filter = {};
    if(role) filter.role = { [Op.eq]: role };
    if (id) filter.id = { [Op.eq]: Number(id) };
    if (!id) filter.id = { [Op.ne]: 100000 };
    if (idCard) filter.idCard = { [Op.like]: `%${idCard}%` };
    if (nickName) filter.nickName = { [Op.like]: `%${nickName}%` };

    const result = await ctx.service.user.list(pageNo, pageSize, filter);
    ctx.body = result
  }

  async add() {
    const { ctx, config } = this;
    let request = ctx.request.body;
    let user = ctx.state.user;
    if (user.role === 'customer') {
      ctx.throw(403, "用户权限不足！");
    }

    const result = await ctx.service.user.add(request);
    ctx.body = result
  }

  async update() {
    const { ctx, config } = this;
    let request = ctx.request.body;
    let user = ctx.state.user;
    if (user.role === 'customer' && user.id !== request.id) {
      ctx.throw(403, "用户权限不足！");
    }
    const result = await ctx.service.user.update(request);
    ctx.body = result
  }

  async reset() {
    const { ctx, config } = this;
    let request = ctx.request.body;
    let user = ctx.state.user;
    if (user.role === 'customer' && user.id !== request.id) {
      ctx.throw(403, "用户权限不足！");
    }
    const result = await ctx.service.user.reset(request);
    ctx.body = result
  }

  async changePassword() {
    const { ctx, config } = this;
    let request = ctx.request.body;

    const result = await ctx.service.user.changePassword(request);
    ctx.body = result
  }

  async delete(){
    const { ctx, config } = this;
    let user = ctx.state.user;
    if (user.role === 'customer') {
      ctx.throw(403, "用户权限不足！");
    }

    const { id } = ctx.query;
    const result = await ctx.service.user.delete(Number(id));
    ctx.body = result
  }

}

module.exports = UserController;

